﻿using AntMovement.Core.IParameter;
using AntMovement.Core.Logic.Base;
using AntMovement.Core.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AntMovement.Core.Logic
{
    public class SingleControl : Prism.Mvvm.BindableBase, ISingleControl
    {
        private string _name;
        public string Name { get => _name; }

        public bool Auto_Open { get; set; }
        public bool Auto_Close { get; set; }
        public bool Manual_Open { get; set; }
        public bool Manual_Close { get; set; }

        private ICoil _coil;

        public bool IOStatus { get => _coil.Status; }
        private NormalOpen _in;

        private string _type = default;
        public string Type => _type;

        private bool _signal;
        public bool Signal => _signal;

        public string In_Text => _model.In_Text;
        public string Out_Text => _model.Out_Text;
        private SingleControlModel _model;

        public SingleControl(IIOParameter io, SingleControlModel model)
        {
            _model = model;
            _name = _model.Name;
            _coil = io.GetCoil(_model.Out_Name);
            _type = _model.Type;
            if (!string.IsNullOrEmpty(_model.In_Name))
            { 
                _in = io.GetNormalOpen(_model.In_Name);
            }
            Manual_Open = _coil.Status;
            Manual_Close = !_coil.Status;
        }

        public void Execute(bool auto, bool manual)
        {
            if ((auto && Auto_Open) || (manual && Manual_Open))
            {
                _coil.Execute(true);
            }
            else if ((auto && Auto_Close) || (manual && Manual_Close))
            {
                _coil.Execute(false);
            }
            if (_in != null)
            {
                SetProperty(ref _signal, _in.Execute(), "Signal");
                if (auto && !manual)
                {
                    Manual_Open = Auto_Open;
                    Manual_Close = Auto_Close;
                }
            }
        }
    }
}
